<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Curl extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 */
	public function test(){
		$url = "http://pan.baidu.com/share/verify?shareid=3193608270&uk=338217192&t=1413028224933&channel=chunlei&clienttype=0&web=1" ;
		$data = array('pwd'=>'sqq6',
				  'vcode'=>''
				 );
				  
		$result = $this->vcurl($url ,$data) ;
		echo "<pre>" ;print_r($result) ;echo "</pre>" ;
	
	}


	public function index($string=NULL)
	{
		ini_set("max_execution_time",0);
		set_time_limit(0);
		$string = (strpos($string,'-')===0)?substr($string,1):$string ;
		$url_query = explode('-',$string) ;
		$uk = (int)!empty($url_query[0])?$url_query[0]:0 ;

		date_default_timezone_set('Asia/Shanghai');
		$this->load->model('mrecords');
		$this->load->model('Mrecordslist');
		$this->load->model('muser');

		$url = 'http://pan.baidu.com/pcloud/friend/getfollowlist?query_uk='.$uk.'&limit=2&start=30&bdstoken=6897ecca28354f48d6f7a61a0ba147c5&channel=chunlei&clienttype=0&web=1' ;
		$out = $this->vcurl($url) ;
		$arr = json_decode($out) ;
		if($arr->total_count > 24){                             // 若数量多于100，要分几页采集
			$perpage = 24 ;                  //  每页数量
			$max = ceil($arr->total_count/24) ;      // 最大页数
			for($i=2;$i<$max;$i++){
				$star = $i*$perpage ;
				$this->follow_list($uk,$star ,$perpage) ;
			}
		}else{
			$star = 0 ;
			$perpage = 24 ;
			$this->follow_list($uk,$star ,$perpage,$arr) ;
		}
	
		echo 'curl ok! <a href="/curl/image" target="blank">同步采集图片</a>' ;
		log_message('error', date('Y-m-d H:i:s').'--采集成功') ;
	}

	public function follow_list($uk, $start=0,$limit=24 ,$arr='')
	{
		if(empty($uk)){
			echo "采集用户id为空" ;
			log_message('error', 'follow_list采集用户id为空') ;
			exit;
		}
		if(empty($arr)){
			$url = 'http://pan.baidu.com/pcloud/friend/getfollowlist?query_uk='.$uk.'&limit='.$limit.'&start='.$start.'&bdstoken=6897ecca28354f48d6f7a61a0ba147c5&channel=chunlei&clienttype=0&web=1' ;
			$out = $this->vcurl($url) ;
			$arr = json_decode($out) ;
		}

		foreach($arr->follow_list as $follow_list){
			if($follow_list->pubshare_count > 0){
				$this->fetchs($follow_list->follow_uk); 
				usleep(10000);                               // 延迟2s，防止频繁访问被屏蔽
			}
		}
	}

	public function fetchs($uk = 0)
	{
		if(empty($uk)){
			echo "采集用户id为空" ;
			log_message('error', '采集用户id为空') ;
			exit;
		}
	// -----------用户信息
		$userurl = 'http://pan.baidu.com/pcloud/user/getinfo?query_uk='.$uk.'&t=1412396542421&bdstoken=6897ecca28354f48d6f7a61a0ba147c5&channel=chunlei&clienttype=0&web=1' ;
		$userinfo = $this->vcurl($userurl) ;
		$info = json_decode($userinfo) ;
		$user_info = $info->user_info ;
		$user_data = array() ;
		$avatar_filepath = 'theme/user/'.date('Ym',time()) ;
		$user_data['uid'] = $user_info->uk ;
		$user_data['username'] = $user_info->uname ;
		$user_data['avatar_url'] = $user_info->avatar_url ;
		$user_data['avatar_url1'] = ''; //$this->getimg($user_info->avatar_url, $avatar_filepath,$user_info->uk) ;
		$user_data['intro'] = $user_info->intro ;
		$user_data['pubshare_count'] = $user_info->pubshare_count ;
		$user_data['album_count'] = $user_info->album_count ;
		$user_data['fans_count'] = $user_info->fans_count ;
		$user_data['follow_count'] = $user_info->follow_count ;
		$user_data['created'] = time() ;
		$user_data['updated'] = time() ;
		$uids = $this->muser->insert($user_data);
		usleep(10000);                               // 延迟2s，防止频繁访问被屏蔽

		//if($uids){                                  // -----------------如果用户未采集过，采集他发布的资源
			// ---------文件列表采集
			$url = 'http://pan.baidu.com/pcloud/feed/getsharelist?category=0&auth_type=1&start=0&limit=100&query_uk='.$uk.'&channel=chunlei&clienttype=0' ;
			$out = $this->vcurl($url) ;
			$arr = json_decode($out) ;
			if($arr->total_count > 100){                             // 若数量多于100，要分几页采集
				$perpage = 100 ;                  //  每页数量
				$max = ceil($arr->total_count/100) ;      // 最大页数
				for($i=0;$i<$max;$i++){
					$star = $i*$perpage ;
					$this->zy($uk,$star ,$perpage) ;
					usleep(5000);                               // 延迟2s，防止频繁访问被屏蔽
				}
			}else{
				$star = 0 ;
				$perpage = 100 ;
				$record_arr = $arr->records ;
				$this->zy($uk,$star ,$perpage,$record_arr) ;
				usleep(5000);                               // 延迟2s，防止频繁访问被屏蔽
			}
		//}
	}

	// ---------同步 yun_records 资源图片到本地
	public function zy($uk, $start=0,$limit=100 ,$record_arr=''){
		if(empty($uk)){
			echo "采集用户id为空" ;exit;
		}
		if(empty($record_arr)){
			$url = 'http://pan.baidu.com/pcloud/feed/getsharelist?category=0&auth_type=1&start='.$start.'&limit='.$limit.'&query_uk='.$uk.'&channel=chunlei&clienttype=0' ;
			$out = $this->vcurl($url) ;
			$arr = json_decode($out) ;
			$record_arr = $arr->records ;
		}
		foreach($record_arr as $record){
			$data = array() ;
			$path_parts = array();
			if($record->feed_type == 'share'){
				$data['feed_type'] = $record->feed_type ;
				$data['category'] = $record->category ;
				$path_parts = @pathinfo($record->title);
				if(!empty($path_parts['extension'])){
					$data['my_category'] = $path_parts['extension'] ;
				}else{
					$data['my_category'] = '' ;
				}
				$data['shareid'] = $record->shareid ;
				$data['data_id'] = $record->data_id ;
				$data['album_id'] = !empty($record->album_id)?$record->album_id:'0' ;
				$data['title'] = $record->title ;
				$data['uk'] = $record->uk ;
				$data['username'] = $record->username ;
				$data['source_uid'] = $record->source_uid ;
				$data['source_id'] = $record->source_id ;
				$data['shorturl'] = !empty($record->shorturl)?$record->shorturl:'' ;
				$data['filecount'] = !empty($record->filecount)?$record->filecount:0 ;
				$filelist = new stdClass() ;
				$filelist = current($record->filelist) ;
				$data['size'] = !empty($filelist->size)?$filelist->size : 0 ;
				$data['path'] = !empty($filelist->path)? $filelist->path:''  ;
				$data['thumburl'] = !empty($filelist->thumburl)?$filelist->thumburl:'' ;
				$data['sign'] = !empty($filelist->sign)? $filelist->sign: '' ;
				$data['isdir'] = !empty($filelist->isdir)? $filelist->isdir: 0 ;
				$data['created'] = !empty($filelist->time_stamp)? $filelist->time_stamp:0  ;
				$data['updated'] = time() ;
				$data['cover_thumb'] = '' ;
				$data['desc'] = '' ;
				$rid = $this->mrecords->insert($data);
				if(!empty($rid)){
					$data1 = array() ;
					$data1['rid'] = $rid ;
					$data1['filelist'] = serialize($filelist) ;
					$data1['created'] = time() ;
					$this->Mrecordslist->insert($data1);
					log_message('error', '===='.$data['title'].'====['.$rid.']'.'--采集成功') ;
				}
			}elseif($record->feed_type == 'album'){
				$data['feed_type'] = $record->feed_type ;
				$data['category'] = $record->category ;
				$path_parts = @pathinfo($record->title);
				if(!empty($path_parts['extension'])){
					$data['my_category'] = $path_parts['extension'] ;
				}else{
					$data['my_category'] = '' ;
				}
				$data['shareid'] = 0 ;
				$data['data_id'] = $record->data_id ;
				$data['album_id'] = $record->album_id ;
				$data['title'] = $record->title ;
				$data['uk'] = $record->uk ;
				$data['username'] = $record->username ;
				$data['source_uid'] = $record->source_uid ;
				$data['source_id'] = $record->source_id ;
				$data['shorturl'] = '' ;
				$data['filecount'] = $record->filecount ;
				$data['size'] = 0 ;
				$data['path'] = '' ;
				$data['thumburl'] = '' ;
				$data['sign'] = 0 ;
				$data['isdir'] = 0 ;
				$data['cover_thumb'] = !empty($record->cover_thumb)? $record->cover_thumb: '' ;
				$data['desc'] = !empty($record->desc)? $record->desc: '' ;
				$data['created'] = time() ;
				$data['updated'] = time() ;
				$rid = $this->mrecords->insert($data);
				if(!empty($rid)){
					$data1 = array() ;
					$data1['rid'] = $rid ;
					$operation = current($record->operation) ;
					$data1['filelist'] = serialize($operation->filelist) ;
					$data1['created'] = time() ;
					$this->Mrecordslist->insert($data1);
					log_message('error', '####'.$data['title'].'####['.$rid.']'.'--采集成功') ;
				}
			}else{}

		}
	}

	// ---------同步 yun_records 资源图片到本地
	public function image()
	{
		ini_set("max_execution_time",0);
		set_time_limit(0);
		$this->load->model('mrecords');
		$this->load->model('Mfile');
		$this->load->model('muser');

		$ds = $this->mrecords->get_image_all();
		$filepath = 'theme/images/'.date('Ym',time()) ;
		foreach($ds as $d){
			$imgurl = '' ;
			$img_url = !empty($d->thumburl)?$d->thumburl:$d->cover_thumb ;
			if(!empty($img_url)){
				$imgurl = $this->getimg($img_url, $filepath,$d->rid) ;
				/*
				if($imgurl){
					$data = array() ;
					$data['rid'] = $d->rid ;
					$data['uid'] = $d->uk ;
					$data['filename'] = $imgurl['filename'] ;
					$data['filepath'] = $imgurl['path'] ;
					$this->Mfile->insert($data);
				}
				*/
			}
			// ---更改图片已下载状态
			$arr = array() ;
			if(!empty($imgurl)){
				$arr['filepath'] = $imgurl ;
			}
			$arr['is_image'] = 1 ;
			$this->mrecords->update($d->rid,$arr) ;
			usleep(2000);                               // 延迟2s，防止频繁访问被屏蔽
		}

		echo "curl images ok!" ;
	}

	function make_dir($path){ 
		if(!file_exists($path)){//不存在则建立 
			$mk=@mkdir($path,0777); //权限 
			@chmod($path,0777); 
		} 
		return true; 
	}

	/*
	 * $url 图片地址
	 * $filepath 图片保存地址
	 * return 返回下载的图片路径和名称
	 */
	function getimg($url, $filepath,$rid) {

		if ($url == '') {
			return false;
		}

		//判断路经是否存在
		$this->make_dir($filepath) ;

		//获得随机的图片名，并加上后辍名
		$filename = sprintf('%010d' ,$rid).'.jpg' ;
		$path = $filepath.'/'.$filename ;

		//读取图片
		$img = $this->vcurl_img($url);
		if(strlen($img)>100){
			//指定打开的文件
			$fp = @fopen($path, 'a');
			//写入图片到指定的文本
			fwrite($fp, $img);
			fclose($fp);
		}
		//return array('path'=>$path , 'filename'=>$filename);
		if(file_exists($path)){
			return $path ;
		}else{
			return ;
		}
	}

	function vcurl($url, $post = '', $cookie = '', $cookiejar = '', $referer = 'http://pan.baidu.com/'){
		$tmpInfo = '';
		//用来存放cookie的文件
		$cookiepath = getcwd().'./'.$cookiejar;
		//初始化curl
		$curl = curl_init();
		//设定目标网址
		curl_setopt($curl, CURLOPT_URL, $url);
		//使用目前所用的浏览器代理
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		//curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		//如果有Ref参数，则设置Referer头，否则自动设置Referer头
		if($referer) {
			curl_setopt($curl, CURLOPT_REFERER, $referer);
		} else {
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		}
		//如果有post数据参数，则方法为POST，并且设置数据，否则为GET
		if($post) {
		//发送一个常规的POST请求，默认类型为：application/x-www-form-urlencoded，表单提交
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
		}
		//如果有cookie参数，则设置
		if($cookie) {
			curl_setopt($curl, CURLOPT_COOKIE, $cookie);
		}
		//如果有cookie文件参数，则设置存取Cookie文件名
		if($cookiejar) {
			curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath);
			curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath);
		}
		//如果是302转移，则返回转移后的网址及内容
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		//设置执行的最大秒数
		curl_setopt($curl, CURLOPT_TIMEOUT, 10);
		//返回内容中是否包含头信息
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//把返回的结果存在文件或者变量中，而不是直接显示在浏览器
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//执行函数后的返回结果
		$tmpInfo = curl_exec($curl);
		//如果出错，显示错误信息
		if (curl_errno($curl)) {
			//$tmpInfo = '<pre><b>错误:</b><br />'.curl_error($curl).'</pre>' ;
			$tmpInfo = '' ;
		}
		//关闭curl对象
		curl_close($curl);
		//返回结果
		return $tmpInfo;
	}

	function vcurl_img($url, $post = '', $cookie = '', $cookiejar = '', $referer = 'http://pan.baidu.com/'){
		$tmpInfo = '';
		//用来存放cookie的文件
		$cookiepath = getcwd().'./'.$cookiejar;
		//初始化curl
		$curl = curl_init();
		//设定目标网址
		curl_setopt($curl, CURLOPT_URL, $url);
		//使用目前所用的浏览器代理
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		//curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		//如果有Ref参数，则设置Referer头，否则自动设置Referer头
		if($referer) {
			curl_setopt($curl, CURLOPT_REFERER, $referer);
		} else {
			curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
		}
		//如果有post数据参数，则方法为POST，并且设置数据，否则为GET
		if($post) {
		//发送一个常规的POST请求，默认类型为：application/x-www-form-urlencoded，表单提交
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
		}
		//如果有cookie参数，则设置
		if($cookie) {
			curl_setopt($curl, CURLOPT_COOKIE, $cookie);
		}
		//如果有cookie文件参数，则设置存取Cookie文件名
		if($cookiejar) {
			curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath);
			curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath);
		}
		//如果是302转移，则返回转移后的网址及内容
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
		//设置执行的最大秒数
		curl_setopt($curl, CURLOPT_TIMEOUT, 2);
		//返回内容中是否包含头信息
		curl_setopt($curl, CURLOPT_HEADER, 0);
		//把返回的结果存在文件或者变量中，而不是直接显示在浏览器
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		//执行函数后的返回结果
		$tmpInfo = curl_exec($curl);
		//如果出错，显示错误信息
		if (curl_errno($curl)) {
			//$tmpInfo = '<pre><b>错误:</b><br />'.curl_error($curl).'</pre>' ;
			$tmpInfo = '' ;
		}
		//关闭curl对象
		curl_close($curl);
		//返回结果
		return $tmpInfo;
	}

}